<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop:'timeOfEntry',order:'ascending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column #default="{row}" label="头像">
            <img :src="row.staffPhoto" alt="" style="width:100%">
          </el-table-column>
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 查询参数 http://loaclhost:8888/#/employees/detail?id=604f764971f93f3ac8f365c7 -->
              <!-- 路径参数 需要路由进行接收 http://loaclhost:8888/#/employees/detail/604f764971f93f3ac8f365c7-->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hCloseDialog">
        <addEmployee ref="addEmployee" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <AssignRole v-if="roleShowDialog" :id="curId" @success="hAssignRoleSuccess" />
      </el-dialog>

    </div>
  </div>
</template>

<script>

import AssignRole from '@/views/employees/assignRole.vue'
import { getEmployee, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
// EmployeeEnum.hireType ===> [{id:1,value:'正式'},{id:2,value:'非正式'}]
import addEmployee from './empDialog.vue'

// const hireType = {}
// EmployeeEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log('hireType', hireType)

export default {
  name: 'EmployeeEnum',
  components: {
    addEmployee,
    AssignRole
  },
  data() {
    return {
      roleShowDialog: false, // 控制分配角色弹层显示和隐藏
      showDialog: false,
      page: 1, // 页码值 默认第一页
      size: 2, // 每页显示的条数
      list: [], // 保存员工数据
      total: 0, // 保存员工总数
      curId: []// 保存员工的id
    }
  },
  created() {
    this.loadEmployee()
  },
  methods: {
    hAssignRoleSuccess() {
      this.roleShowDialog = false
    },
    hAssignRole(id) {
      this.curId = id
      this.roleShowDialog = true
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      // 如果list中有数组 才需要生成表头
      if (!one) return // 没有数据 终止程序
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })
      // 生成data数据
      const data = list.map(item => {
        console.log(item.formOfEmployment, 'item.formOfEmployment')
        const key = item.formOfEmployment
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      return { header: header, data: data }
    },
    // 导入功能的关键代码
    // 思路
    // - 1  发送请求获取数据
    // - 2. 将获取到数据进行格式化处理，处理成生成excel文件需要的格式的数据（将英文转中文）
    // - 3. 调用admin中关键的函数export_json_to_excel，生成excel文件
    async handleDownload() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployee(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        // 如果删除第最后一页（例如4）的最一条数据之后，页面会显示不正常
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployee()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    hCloseDialog() {
      // 相当于是在父组件中去执行子组件中方法
      // 去清空 子组件中的表单数据和校验结果
      // 子组件.resetForm()
      console.log('在父组件中获取子组件的引用', this.$refs.addEmployee)
      this.$refs.addEmployee.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployee()
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployee()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployee()
    },
    // 格式化聘用形式的函数
    formOfEmploymentFormat(data) { // data =>  1 || 2
    // 将传入的1 或 2 转化为正式 或 非正式
    // EmployeeEnum.hireType ===> [{id:1,value:'正式'},{id:2,value:'非正式'}]
      // return EmployeeEnum.hireType.find(item => item.id === data).value
      // 一定要返回格式化好的数据  正式 || 非正式
      return hireType[data] || '未知'
    },
    async loadEmployee() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log(res, 'loadEmployee')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
